package com.spider.controller;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.spider.domain.Movie;
import com.spider.service.MovieServiceI;
import com.spider.util.SpiderYangGuang;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author HQJ
 * @since 2021-02-02
 */
@Controller
@RequestMapping("/mc")
public class MovieController extends BaseController{

    @Resource(name = "movieServiceI")
    private MovieServiceI msi;


    @RequestMapping("/index")
    public String index(){
        return prefix+"/spider/movie/index"+suffix;
    }

    @RequestMapping("/{page}/{id}")
    public String edit(@PathVariable(value = "id") int id,
                       @PathVariable(value = "page") String page,
                       ModelMap mmap){
        Movie m = msi.getById(id);
        if(m!=null){
            //设置属性，传递到打开的页面
            mmap.addAttribute("m",m);
        }
        return prefix+"/spider/movie/"+page+suffix;
    }


    @RequestMapping("/find")
    @ResponseBody
    public Map<String,Object> find(Movie m){
        QueryWrapper<Movie> qw = new QueryWrapper<>();
        if(m.getMovieName()!=null){
            qw.like("movie_name",m.getMovieName());
        }
        List<Movie> list = msi.list(qw);
        Map<String,Object> map = new HashMap<>();
        map.put("code",0);
        map.put("msg","数据查询成功");
        map.put("data",list);
        map.put("size",list.size());

        return map;
    }


    @RequestMapping("/save")
    @ResponseBody
    public Map<String, Object> save(){
        List<Object> list = SpiderYangGuang.test();
        String json = JSON.toJSONString(list);
        List<Movie> ms = JSON.parseArray(json,Movie.class);
        boolean b = msi.saveBatch(ms);

        Map<String,Object> map = new HashMap<>();
        map.put("msg","爬取"+(b?"成功":"失败"));
        map.put("is",b);
        return map;
    }

    @RequestMapping("/saveOrUpdate")
    @ResponseBody
    public Map<String,Object> saveOrUpdate(Movie m){
        boolean b = msi.saveOrUpdate(m);
        Map<String,Object> map = new HashMap<>();
        map.put("msg","执行"+(b?"成功":"失败"));
        map.put("is",b);

        return map;
    }

    @RequestMapping("/remove/{id}")
    @ResponseBody
    public Map<String,Object> remove(@PathVariable(value = "id") int id){
        boolean b = msi.removeById(id);
        Map<String,Object> map = new HashMap<>();
        map.put("msg","删除"+(b?"成功":"失败"));
        map.put("is",b);
        return map;
    }

}

